#!/bin/bash

main()
{
  for command in which cat grep tr sed rm curl tidy gcc plowdown; do
    check-command $command
  done

  if [ $# -lt 1 ]; then
    error "Faltan argumentos."
  elif [ $# -gt 1 ]; then
    error "Demasiados argumentos."
  fi

  local url=$1

	get-proxies-list 1 | sed '1,2d' | while read proxy; do
		check-proxy $proxy

		if [ "$?" == "1" ]; then
			echo $url
			download $proxy $url
			break
		fi
	done
}

download()
{
	local proxy=$1
	local url=$2

	export http_proxy=$proxy
	plowdown $url

	if [ "$?" == "1" ]; then
    error "No se pudo descargar el enlace solicitado."
	fi
}

error()
{
  printf "$*\n"
  exit 1
}

check-proxy()
{
	local proxy=$*
	local url=http://www.google.com/
	local null=/dev/null

	printf "Probando el proxy $proxy: "

	curl --proxy $proxy $url -o $null --stderr $null

	if [ "$?" == "0" ]; then
		printf "Listo.\n"
		return 1
	else
		printf "No funciona.\n"
		return 0
	fi
}

check-command()
{
  which $* > /dev/null

  if [ "$?" != "0" ]; then
    printf "No se encontró el comando $*.\n"
    exit 2
  fi
}

get-proxies-page()
{
	url=http://www.freeproxylists.net/?s=rs\&page=${1:-1}
	
	cat<<EOF > output.c
	#include <curl/curl.h>
	#include <stdio.h>
	
	int main (int argc, char *argv[]) {
EOF
	
	curl $url 2> /dev/null | grep document.write | tr "'" "\n" | grep ^% |
	sed 's/^/\tconst char *code = "/;s/$/";/' >> output.c
	
	
	cat<<EOF >> output.c
		CURL *curl = curl_easy_init ();
		fprintf (stdout, "%s\\n", curl_easy_unescape (curl, code, 0, NULL));
	 	curl_easy_cleanup (curl);
		return 0;
	}
EOF
	
	gcc output.c -o output -lcurl
	
	./output | tidy 2>&1 | sed -n '/<table/,/<\/table>/p' | grep -A2 '^<tr' | grep '<td' |
	sed 's/"center">/>:/;s/<td>/|/;s/<[^>]\+>//g' | tr -d "\n" | tr '|' "\n" | grep ^[0-9]
	
	rm -f output output.c
}

get-proxies-list()
{
	pages=${1:-10}

	for ((x = 1; x <= $pages; x++)); do
		get-proxies-page $x
	done
}

IFS='|'
main $*

exit 0
